package com.pine.admin.modules.system.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.pine.admin.modules.system.entity.SysUserEntity;
import com.pine.admin.modules.system.service.RedisService;
import com.pine.admin.modules.system.service.SysService;
import com.pine.admin.modules.system.service.SysUserService;
import com.pine.admin.modules.system.entity.ActiveUserEntity;
import com.pine.admin.modules.system.service.RedisService;
import com.pine.admin.modules.system.service.SysService;
import com.pine.common.binder.BaseController;
import com.pine.common.dto.Page;
import com.pine.common.dto.Result;
import com.pine.common.utils.CookieUtil;
import com.pine.common.utils.MD5Util;
import com.pine.common.utils.UUIDGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.pine.admin.modules.system.entity.SysUserEntity;
import com.pine.admin.modules.system.service.SysUserService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * @author Pine
 * @email 771190883@qq.com
 * @date 2018-06-21 13:55:06
 */
@RestController
@RequestMapping("system/sysuser")
@Slf4j
public class SysUserController extends BaseController {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysService sysService;

    @Autowired
    private RedisService redisService;

    /**
     * <p>获取全部记录。</p>
     */
    @RequestMapping(value = "/all", method = RequestMethod.GET)
    public Result all( SysUserEntity record) {

        List<SysUserEntity> pp = sysUserService.getSysUserList(record);
        return new Result(true, pp);
    }
    @RequestMapping(value = "/list", method = RequestMethod.POST)

    public Result save(@RequestBody List<SysUserEntity> record) {

        List<SysUserEntity> list = record;

        return null;
    }
    /**
     * <p>根据Id。</p>
     */
    @RequestMapping(value = "/getSysUserEntity", method = RequestMethod.GET)
    public Result getSysUserEntity(@RequestParam(required = false, value = "id") String id) {

        SysUserEntity data = sysUserService.getSysUserById(id);
        return new Result(true, data);
    }

    /**
     * <p>根据条件获取。</p>
     */
    @RequestMapping(value = "/getOne", method = RequestMethod.GET)
    public Result getOne(SysUserEntity record) {

        SysUserEntity data = sysUserService.getSysUser(record);
        return new Result(true, data);
    }

    /**
     * <p>分页查询。</p>
     */
    @RequestMapping(value = "/page", method = RequestMethod.GET)
    public Result page(Page page, SysUserEntity record) {

        Map<String, Object> result = new HashMap<>();

        List<SysUserEntity> pp = sysUserService.getSysUserByPage(page, record);

        result.put("page", page);
        result.put("pp", pp);
        return new Result(true, result);
    }

    /**
     * <p>保存。</p>
     */
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public Result save(@RequestBody SysUserEntity record) {

        boolean num = sysUserService.createSysUser(record);
        if (num) {
            return new Result(true, record.getId());
        }
        return new Result(false, "保存异常");
    }

    /**
     * <p>更新信息。</p>
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public Result updateSysUser(SysUserEntity record) {

        boolean num = sysUserService.updateSysUser(record);
        if (num) {
            return new Result(true, "保存成功");
        }
        return new Result(false, "保存异常");
    }

    /**
     * <p>删除。</p>
     */
    @RequestMapping(value = "/del", method = RequestMethod.POST)
    public Result deleteSysUser(@RequestParam(required = true, value = "id") String id) {

        boolean num = sysUserService.deleteSysUser(id);
        if (num) {
            return new Result(true, "删除成功");
        }
        return new Result(false, "删除异常");
    }


    @RequestMapping(value = "login", method = RequestMethod.POST)
    public Result login(HttpServletRequest request, HttpServletResponse response, String userCode, String password) throws Exception {


        log.info("password::::"+MD5Util.getMD5(password));
        if (null == userCode || "".equals(userCode)) {
            return new Result(false, "用户名或密码错误");
        }

//        String authCode = (String) request.getSession(true).getAttribute("rand");
//        if (!code.toLowerCase().equals(authCode)) {
//            return new Result(false, "验证码错误");
//        }
        //调用Service校验用户账号和密码的正确性

        /**
         * 认证过程： 根据用户身份(账号)查询数据库，如果查询不到则用户不存在
         * 对输入的密码和数据库密码进行比对，如果一致则认证通过
         */

        // 根据用户账号查询数据库
        SysUserEntity sysUser = new SysUserEntity();
        sysUser.setUsercode(userCode);
        sysUser = sysUserService.getSysUser(sysUser);

        // 数据库密码（MD5加密后的密码）

        if (null == sysUser) {
            return new Result(false, "用户账号或者密码错误");
        }

        String password_db = sysUser.getPassword();

        // 对输入的密码和数据库密码进行比对，如果一致，认证通过
        // 对页面输入的密码进行MD5加密

        String password_input_md5 = MD5Util.getMD5(password);

        if (!password_db.equalsIgnoreCase(password_input_md5)) {
            //抛出异常
            return new Result(false, "用户名或密码错误");
        }

        ActiveUserEntity activeUser = sysService.authenticat(userCode, password);

        //如果Service校验通过，将用户身份记录到Session

        request.getSession(true).setAttribute("activeUser", activeUser);
        request.getSession(true).setAttribute("superUserId", activeUser.getUserId());


        String userId = sysUser.getId() + "";

        request.getSession(true).setAttribute("superUserName", sysUser.getUsername());
        //返回用户信息

        //cookie生命周期设置为20小时

        int maxAge = 7 * 24 * 60 * 60;

        String uidToken = "uidToken"+activeUser.getUserId();

        String token = UUIDGenerator.genUUIDRemoveSep();

        activeUser.setUidToken(token);

        redisService.remove(uidToken);
        redisService.set(uidToken,token);

        return new Result(true, activeUser);
    }

    @RequestMapping(value = "logout", method = RequestMethod.POST)
    public Result logout(HttpServletRequest request, HttpServletResponse response) {

        //cookie生命周期设置为20小时
        int maxAge = -1;
        CookieUtil.addCookie(response, "superUserId", "-1", maxAge);
        CookieUtil.addCookie(response, "superUserName", "-1", maxAge);

        request.getSession().invalidate();
        //设置登陆状态
        return new Result(true, "退出成功");

    }
}
